import json_loader
import layout_algorithm

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

# container of vad data
class VadData(object, metaclass=Singleton):

    def __init__(self, pid):
        '''
        load the init json file
        '''
        self.pid = pid
        self._firstJsonName = r"json/vad0.json"
        self._network_history = []

        self._loader = json_loader.JsonLoader()
        network = self._loader.loadFirstImage(self._firstJsonName, self.pid)

        # layout the graph
        layout = layout_algorithm.LayoutAlgorithmIGraph()
        layout.execute(network)

        self._network_history.append(network)
        self._network_pos = 0
    
    def next(self):
        # maybe fail, but self._pos is not move when fail
        if self._network_pos+1 < len(self._network_history):
            self._network_pos += 1
            return self.current()
        else:
            # load new image json
            num = self._network_pos+1
            filename = r"json/vad"+str(num)+".json"
            network = self._loader.loadFirstImage(filename, self.pid)

            if network:
                # layout the graph
                layout = layout_algorithm.LayoutAlgorithmIGraph()
                layout.execute(network)

                self._network_history.append(network)
                self._network_pos += 1
                return self.current()
    
    def prev(self):
        if 0 <= self._network_pos-1 < len(self._network_history):
            self._network_pos -= 1
            return self.current()
        
        print("VadData out of range")
        return None


    def current(self):
        return self._network_history[self._network_pos]

    def __len__(self):
        return len(self._network_history)
    

    def __getitem__(self, pos):
        if isinstance(pos, int) and 0 <= pos < len(self._network_history):
            return self._network_history[pos]
        print("VadData out of range")
        return None
    
    def getCurrentPos(self):
        return self._network_pos